package com.yutian.selfservice.auth.controller;

import com.yutian.selfservice.auth.domain.SysUser;
import com.yutian.selfservice.auth.domain.entity.AjaxResult;
import com.yutian.selfservice.auth.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * 登录验证
 * 
 * @author yutian
 */
@Controller
public class SysLoginController extends BaseController
{

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            HashMap<String,String> loginvo = new HashMap<>();
            String sid = (String) subject.getSession().getId();
            //如果登录没有出现异常的话,就可以通过getPrincinpal()获取登录用户
            SysUser user= (SysUser)subject.getPrincipal();
            //获取sessionId
            String sessionId = (String) subject.getSession().getId();
            loginvo.put("JSESSIONID",sessionId);
            return success(loginvo);
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    @ResponseBody
    public AjaxResult unauth()
    {
        return error("用户未登录");
    }
}
